package com.yfree.utils;

import com.yfree.YConfig;
import com.yfree.activities.YActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

public class YLogUtils {
    public static void out(YActivity yActivity, String logContent) {
        PrintWriter writer = null;
        FileOutputStream outputStream = null;
        try {
            if (yActivity.yBasePath == null) {
//                context.yBasePath = Environment.getExternalStorageDirectory().getAbsolutePath() + YConfig.PROJECTBASEDIR;
                yActivity.yBasePath = yActivity.context.getExternalFilesDir(YConfig.YFreeDir).getAbsolutePath() + YConfig.PROJECTBASEDIR;
                File readyFile = new File(yActivity.yBasePath);
                if (!readyFile.exists())
                    if (!readyFile.mkdirs()) return;
            }
            String logPath = yActivity.yBasePath + YConfig.LOGPATH + "/";
            File logBaseFile = new File(logPath);
            if (!logBaseFile.exists()) {
                if (!logBaseFile.mkdirs()) {
                    return;
                }
            }
            int logFileIndex = 1;
            File file = new File(logPath + YConfig.LOG_FILE_NAME + logFileIndex + ".ylog");
            // 判断之前的日志如果大于1M，则创建新日志文件
            while (file.exists() && file.length() / 1024.0 > YConfig.LOG_FILE_SIZE) {
                file = new File(logPath + YConfig.LOG_FILE_NAME + (++logFileIndex) + ".ylog");
            }
            // 开始写日志
            outputStream = new FileOutputStream(file, true);
            writer = new PrintWriter(outputStream);
            writer.println("<<<=====================>>>");
            writer.println();
            writer.println(logContent);
            writer.println();
        } catch (Exception ignored) {
        } finally {
            if (writer != null) {
                writer.flush();
                writer.close();
            }
            if (outputStream != null) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException ignored) {
                }
            }
        }
    }
}
